package com.caszx.chargingpile.activity;

import android.animation.ObjectAnimator;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewStub;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.alibaba.fastjson.JSONException;
import com.app.base.app.BaseTopBarNetActivity;
import com.app.utils.DiskUser;
import com.app.utils.SystemHelper;
import com.caszx.chargingpile.R;
import com.caszx.chargingpile.http.ConstantUrl;
import com.caszx.chargingpile.utils.DialogHelp;
import com.caszx.chargingpile.utils.SnackbarHelp;
import com.jakewharton.rxbinding.view.RxView;
import com.rey.material.app.DialogFragment;

import org.json.JSONObject;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import http.okhttp.OkHttpUtils;
import http.okhttp.callback.JsonCallback;
import okhttp3.Call;
import rx.functions.Action1;

/**绑定会员卡*/
public class UserBindVipActivity extends BaseTopBarNetActivity{

    private  static  int DURATION = 500;
    private  int SCREEN_WIDTH;
    //分步绑定，绑定后只有mViewStep01不为null
    private View mViewStep01,mViewStep02;

    private RelativeLayout card_bg_layout ;
    private TextView btn_card_unbind ;//解除绑卡
    private TextView txt_card_num ;//卡号
    private View center_line ;//卡号
    private TextView txt_remain ;//余额
    private TextView txt_consume ;//消费
    private TextView txt_bind_info ;//开通会员卡 立享优惠
    private ImageButton btn_add_card ;//开通会员卡 立享优惠
    private LinearLayout menu_layout ;
    private TextView txt_credit ;
    private TextView txt_passwd ;

    private TextView edit_bind_card ;
    private TextView edit_bind_passwd ;


    @Override
    protected void init() {
        SCREEN_WIDTH = SystemHelper.getScreenWidth(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setCenterTitle(R.string.string_bind_vip_card);
    }


    @Override
    protected void onLoad() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_CARD_DEATIL)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        showErrorView(R.string.error_network);
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                showErrorView();
                            } else {
                                try {
                                    showContentView();
                                    parserBind(response);
                                } catch (JSONException e) {
                                    showErrorView(R.string.error_parser_json);
                                }
                            }
                        }
                    }
                });
    }

    @Override
    protected View initOnloadedView() {
        View view = getLayoutInflater().inflate(R.layout.activity_bind_vip, null);
        initBindView(view);
        return view;
    }

   private void parserBind(JSONObject jsonObject){
       if(jsonObject!=null){
           DecimalFormat decimalFormat = new DecimalFormat("##.##");
           double balance = jsonObject.optDouble("balance");
           double countCost = jsonObject.optDouble("countCost");
           double status = jsonObject.optInt("status");
           String svcardNo = jsonObject.optString("svcardNo");

           if(status==1){
               //已经绑定
               txt_card_num.setVisibility(View.VISIBLE);
               txt_remain.setVisibility(View.VISIBLE);
               txt_consume.setVisibility(View.VISIBLE);
               center_line.setVisibility(View.VISIBLE);
               btn_card_unbind.setVisibility(View.VISIBLE);
               menu_layout.setVisibility(View.VISIBLE);
               txt_bind_info.setVisibility(View.GONE);
               btn_add_card.setVisibility(View.GONE);

               txt_card_num.setText(svcardNo);
               txt_remain.setText("余额 "+decimalFormat.format(balance));
               txt_consume.setText("总消费 "+decimalFormat.format(countCost));
           }else if(status==0){
               //未绑定卡
               txt_bind_info.setVisibility(View.VISIBLE);
               btn_add_card.setVisibility(View.VISIBLE);

               txt_card_num.setVisibility(View.GONE);
               txt_remain.setVisibility(View.GONE);
               txt_consume.setVisibility(View.GONE);
               center_line.setVisibility(View.GONE);
               btn_card_unbind.setVisibility(View.GONE);
               menu_layout.setVisibility(View.GONE);
           }
       }else{
           txt_bind_info.setVisibility(View.VISIBLE);
           btn_add_card.setVisibility(View.VISIBLE);

           txt_card_num.setVisibility(View.GONE);
           txt_remain.setVisibility(View.GONE);
           txt_consume.setVisibility(View.GONE);
           center_line.setVisibility(View.GONE);
           btn_card_unbind.setVisibility(View.GONE);
           menu_layout.setVisibility(View.GONE);
       }
   }

    /**初始化绑定*/
    private void initBindView(final View view){
        if(mViewStep01 == null){
        ViewStub stub = (ViewStub)view.findViewById(R.id.stubView01);
        mViewStep01 = stub.inflate();
        card_bg_layout = (RelativeLayout) mViewStep01.findViewById(R.id.card_bg_layout);
        btn_card_unbind = (TextView) mViewStep01.findViewById(R.id.btn_card_unbind);
        txt_card_num = (TextView) mViewStep01.findViewById(R.id.txt_card_num);
        center_line =  mViewStep01.findViewById(R.id.center_line);
        txt_remain = (TextView) mViewStep01.findViewById(R.id.txt_remain);
        txt_consume = (TextView) mViewStep01.findViewById(R.id.txt_consume);
        txt_bind_info = (TextView) mViewStep01.findViewById(R.id.txt_bind_info);
        btn_add_card = (ImageButton) mViewStep01.findViewById(R.id.btn_add_card);
        menu_layout = (LinearLayout) mViewStep01.findViewById(R.id.menu_layout);
        txt_credit = (TextView) mViewStep01.findViewById(R.id.txt_credit);
        txt_passwd = (TextView) mViewStep01.findViewById(R.id.txt_passwd);


            RxView.clicks(txt_credit).throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            //充值记录
                            Intent intent = new Intent(UserBindVipActivity.this,UserChargeRecordActivity.class);
                            startActivity(intent);
                        }
                    });

            RxView.clicks(txt_passwd).throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            //重置会员卡密码
                            Intent intent = new Intent(UserBindVipActivity.this,UserSignUpPassWdActivity.class);
                            intent.putExtra("TYPE",UserSignUpPassWdActivity.USER_MD_VIP_CARD);
                            startActivity(intent);

                        }
                    });
            RxView.clicks(btn_add_card).throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                            translationX(mViewStep01,0,-SCREEN_WIDTH);
                            initInputCard(view);
                            translationX(mViewStep02,SCREEN_WIDTH,0);
                        }
                    });
            RxView.clicks(btn_card_unbind).throttleFirst(500, TimeUnit.MILLISECONDS)
                    .subscribe(new Action1<Void>() {
                        @Override
                        public void call(Void aVoid) {
                             DialogHelp.showDialogOnlyMesg(UserBindVipActivity.this,"确定解除?", new DialogHelp.DialogActionClickListener() {
                                @Override
                                public void onPositiveActionClicked(DialogFragment fragment) {
                                    unbindCard();
                                }
                                @Override
                                public void onNegativeActionClicked(DialogFragment fragment) {
                                }
                            });
                        }
                    });
        }
    }

    /**初始化输入卡号*/
    private void initInputCard(View view){
        if(mViewStep02==null){
            ViewStub stub = (ViewStub)findViewById(R.id.stubView02);
            mViewStep02 = stub.inflate();
            edit_bind_card = (TextView) mViewStep02.findViewById(R.id.edit_bind_card);
            edit_bind_passwd = (TextView) mViewStep02.findViewById(R.id.edit_bind_passwd);
            mViewStep02.findViewById(R.id.btn_bind_next).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String cardNo = edit_bind_card.getText().toString().trim();
                    String passwd = edit_bind_passwd.getText().toString().trim();

                    if(TextUtils.isEmpty(cardNo)){
                        SnackbarHelp.showSnackbarMsg(UserBindVipActivity.this,"请输入卡号");
                        return;
                    }

                    if(TextUtils.isEmpty(passwd)){
                        SnackbarHelp.showSnackbarMsg(UserBindVipActivity.this,"请输入密码");
                        return;
                    }

                    bindCard(cardNo,passwd);
                }
            });
        }

    }


    private  void bindCard(String num,String passwd){
        showProgressDialog("绑定中...");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        params.put("pwd", passwd);
        params.put("svcardNo", num);
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_BIND_CARD)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp. showSnackbarMsg(UserBindVipActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                SnackbarHelp.showSnackbarMsg(UserBindVipActivity.this,resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    edit_bind_card.setText(null);
                                    edit_bind_passwd.setText(null);
                                    translationX(mViewStep01,-SCREEN_WIDTH,0);
                                    translationX(mViewStep02,0,SCREEN_WIDTH);
                                    onLoad();
                                } catch (JSONException e) {
                                    SnackbarHelp. showSnackbarMsg(UserBindVipActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }



    private  void unbindCard(){
        showProgressDialog("解绑中...");
        HashMap<String, String> params = new HashMap<>();
        params.put("token", DiskUser.getStringValueByKey(this, "token"));
        OkHttpUtils.post()
                .url(ConstantUrl.URL_USER_UNBIND_CARD)
                .params(params)
                .tag(this)
                .build()
                .execute(new JsonCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        dissmissProgressDialog();
                        SnackbarHelp.showSnackbarMsg(UserBindVipActivity.this,getResources().getString(R.string.error_network));
                    }

                    @Override
                    public void onResponse(JSONObject response) {
                        dissmissProgressDialog();
                        JSONObject resultJsonObject = response.optJSONObject("result");
                        if (resultJsonObject != null) {
                            int code = resultJsonObject.optInt("code");
                            if (code < 0) {
                                //error
                                // DialogHelp.showDialogOnlyMesg(resultJsonObject.optString("msg"), null);
                                SnackbarHelp.showSnackbarMsg(UserBindVipActivity.this,resultJsonObject.optString("msg"));
                            } else {
                                try {
                                    parserBind(null);
                                } catch (JSONException e) {
                                    SnackbarHelp. showSnackbarMsg(UserBindVipActivity.this,getResources().getString(R.string.error_parser_json));
                                }
                            }
                        }
                    }
                });
    }


    private void translationX(View view,float start,float end){
        ObjectAnimator objectAnimator = android.animation.ObjectAnimator.ofFloat(view,View.TRANSLATION_X,start,end);
        objectAnimator.setDuration(DURATION);
        objectAnimator.start();
    }
}
